import { Notification } from "element-ui";
import { getToken } from "@/utils/auth";
 
let socket = null, pointSocket = null;//实例对象
let lockReconnect = false; //是否禁止重连
let timeout = 20 * 1000; //20秒一次心跳
let timeoutObj = null; //心跳倒计时
let serverTimeoutObj = null; //服务心跳倒计时
let timeoutNum = null; //断开 重连倒计时
let id = '';
let type = '';
let sessionId = '';
let token = getToken();

// const baseUrl = 'ws://192.168.1.199:8090/prod-api/'; //本地2
// const baseUrl = 'ws://172.16.250.42:9090/prod-api/'; //测试环境88
// const baseUrl = 'ws://172.16.250.42:8090/prod-api/'; //开发环境86
const baseUrl = 'ws://172.16.250.87:9090/prod-api/'; //188-1
// const baseUrl = 'ws://172.16.250.86:9090/prod-api/'; //186-2
 
const initWebSocket = async (taskId, targetType) => {
  id = taskId
  type = targetType
  token = getToken()
  sessionId = `${taskId}_${(new Date()).valueOf()}`
  if ("WebSocket" in window) {
    const wsUrl = `${baseUrl}inspectionWs/pcTrack/${id}/${type}/${sessionId}?token=${token}`; //任务中轨迹实时数据
    const pointWsUrl = `${baseUrl}inspectionWs/pcPoint/${id}/${sessionId}?token=${token}`;  //任务中点位的实时数据
    socket = new WebSocket(wsUrl);
    pointSocket = new WebSocket(pointWsUrl);
    //轨迹
    socket.onerror = webSocketOnError;
    socket.onmessage = webSocketOnMessage;
    socket.onclose = closeWebsocket;
    socket.onopen = openWebsocket;
    //点位
    pointSocket.onerror = webSocketOnError;
    pointSocket.onmessage = pointSocketOnMessage;
    pointSocket.onclose = closeWebsocket;
    pointSocket.onopen = openPointWebsocket;
    // console.log(wsUrl, 1111)
  } else {
    Notification.error({
      title: "错误",
      message: "您的浏览器不支持websocket，请更换Chrome或者Firefox",
    });
  }
}
 
//建立连接
const openWebsocket = (e) => {
  console.log(lockReconnect, '<=======lockReconnect')
  console.log('webSocket连接成功')
  start();
}

//建立连接
const openPointWebsocket = (e) => {
  console.log('point webSocket连接成功')
  start();
}

const start = ()=> {
  //开启心跳
  // timeoutObj && clearTimeout(timeoutObj);
  // serverTimeoutObj && clearTimeout(serverTimeoutObj);
  // timeoutObj = setTimeout(function() {
  //   //这里发送一个心跳，后端收到后，返回一个心跳消息
  //   // console.log(socket, '<===========socket')
  //   if (socket.readyState == 1) {
  //     //如果连接正常
  //     // socket.send("heartbeat");
  //   } else {
  //     //否则重连
  //     reconnect();
  //   }
  //   // serverTimeoutObj = setTimeout(function() {
  //   //   //超时关闭
  //   //   socket.close();
  //   // }, timeout);
  // }, timeout);
}
 
//重新连接
const reconnect =() => { 
  if (lockReconnect) {
    return;
  }
  lockReconnect = true;
  //没连接上会一直重连，设置延迟避免请求过多
  timeoutNum && clearTimeout(timeoutNum);
  timeoutNum = setTimeout(function() {
    //新连接
    initWebSocket(id, type);
    lockReconnect = false;
  }, 5000);
}
 
//重置心跳
const reset =() => {
  //清除时间
  clearTimeout(timeoutObj);
  clearTimeout(serverTimeoutObj);
  //重启心跳
  start();
}
 
const sendWebsocket =(e) =>{
  // socket.send(`我发消息了`);
}
 
const webSocketOnError =(e) => {
  console.log('webSocket连接发生错误')
  initWebSocket(id, type);
  reconnect();
}
 
//服务器返回的数据
const webSocketOnMessage=(e) => {
  //判断是否登录
  if (getToken()) {
    //window自定义事件[下面有说明]
    window.dispatchEvent(
      new CustomEvent("onmessageWS", {
        detail: {
          data: JSON.parse(e?.data),
        },
      })
    );
  }
  // reset();
}

//服务器返回的数据
const pointSocketOnMessage=(e) => {
  //判断是否登录
  if (getToken()) {
    //window自定义事件[下面有说明]
    window.dispatchEvent(
      new CustomEvent("onmessagePointWS", {
        detail: {
          data: JSON.parse(e?.data),
        },
      })
    );
  }
  // reset();
}
 
const closeWebsocket=(e) => { 
  console.log(lockReconnect, '<=======ws关闭了')
  // pointSocket.close();
  // socket.close();
  // reconnect();
}
 
//断开连接
const close =() => {
//WebSocket对象也有发送和关闭的两个方法，只需要在自定义方法中分别调用send()和close()即可实现。
  console.log("socket已经关闭");
  // lockReconnect = true;
  // clearTimeout(timeoutObj);
  // clearTimeout(serverTimeoutObj);
  // setTimeout(() => {
  //   lockReconnect = false;
  // }, 3000)
  if (socket) {
    socket.close();
  }
  if (pointSocket) {
    pointSocket.close();
  }
}

//具体问题具体分析,把需要用到的方法暴露出去
export default { initWebSocket, sendWebsocket, webSocketOnMessage, pointSocketOnMessage, close };